package com.heima.leetcode.datastructure.binarytree;


import java.util.LinkedList;
import java.util.function.Consumer;

/**
 * <strong>层序遍历</strong>
 * @author 勾新杰
 * @version 1.0
 * @date 2024/9/8 22:44
 */
public class LevelOrderTraversal {
    @SuppressWarnings("all")
    public static void levelOrder(TreeNode root, Consumer<Integer> consumer) {
        if (root == null) {
            return;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++){
                TreeNode node = queue.poll();
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
                consumer.accept(node.val);
            }
        }
    }
}
